<template>
  <el-dialog
    :width="1000"
    v-model="formVisible"
    title="抽查对象"
    @close="formCancel"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row :gutter="40" style="width: 100%">
        <el-col :span="12">
          <el-form-item label="抽查时间" prop="spotCheckTime">
            <div >
              <el-date-picker
                v-model="form.spotCheckTime"
                format="YYYY-MM-DD"
                dateFormat="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择抽查时间"
                type="datetimerange"
                style="width: 342px"
                startPlaceholder="开始时间"
                endPlaceholder="结束时间"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织形式" prop="orgFrom">
            <MSelect
              v-model="form.orgFrom"
              placeholder="请选择"
              :options="orgFromOptions"
              class="select"
              multiple
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查人员" prop="operPersonIds">
            <SamplingPersonnel v-model="form.operPersonIds" class="select" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽查事项" prop="itemNames">
            <div style="display: flex; align-items: center; width: 100%">
              <MSelect
                v-model="form.itemNames"
                placeholder="请选择"
                :options="itemNamesOptions"
                class="select"
                style="flex: 1"
                multiple
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: flex-end; width: 100%">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submitForm" v-loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <PersonnelSelection ref="PersonnelSelectionRef" />

</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import PersonnelSelection from '../../personnelSelection/personnelSelection.vue'
import { intelligentSave, getManagerChild } from '@/api/spotCheck/spotCheck'
import SamplingPersonnel from '@/views/spotCheck/components/samplingPersonnel/samplingPersonnel.vue'

type Options = {
  value: number
  label: string
}

const orgFromOptions = ref<Options[]>([])
const itemNamesOptions = ref<Options[]>([])

const emit = defineEmits(['reload'])
onMounted(() => {
  getManagerChild('OrganizationalForm').then((res) => {
    orgFromOptions.value = res.data.map((i) => ({
      value: Number(i.id),
      label: i.name
    }))
  })
  getManagerChild('spotCheck').then((res) => {
    itemNamesOptions.value = res.data.map((i) => ({
      value: Number(i.id),
      label: i.name
    }))
  })
})

const formVisible = ref(false)

type Ids = string | number

interface SpotCheckForm {
  spotCheckTime: Date[] | undefined // 抽查时间
  orgFrom: Ids[] // 组织形式
  orgFromIds: Ids
  itemNames: Ids[] // 抽查事项
  operPersonIds: number[] // 抽检人员
  types: number
  sorgSpotCheckPlanId?: Ids
  sorgSpotCheckId?: Ids
}

//新增
const form = reactive<SpotCheckForm>({
  spotCheckTime: undefined, //抽查时间
  orgFrom: [], //组织形式
  orgFromIds: '',
  itemNames: [], //抽查事项
  operPersonIds: [], //抽检人员
  types: 0
})

const rules = ref({
  spotCheckTime: [{ required: true, message: '请选择', trigger: 'change' }],
  orgFrom: [{ required: true, message: '请选择', trigger: 'change' }],
  itemNames: [{ required: true, message: '请选择', trigger: 'change' }],
  operPersonIds: [{ required: true, message: '请选择', trigger: 'change' }]
})

const save = () => {
  formVisible.value = true
}

const formCancel = () => {
  formVisible.value = false
}

type Infos = {
  orgId: string
  orgName: string
  sorgType: number
}

type Data = {
  sorgSpotCheckPlanId: number
  infos: Infos[]
  other: {
    types: number
  }
}

const otherData = ref<Data>()
const show = (data: Data, type = 0) => {
  formVisible.value = true
  clearForm()
  form.sorgSpotCheckPlanId = data.sorgSpotCheckPlanId
  form.types = type
  otherData.value = data
}

const PersonnelSelectionRef = ref(false)

const loading = ref(false)
const ruleFormRef = ref()
const submitForm = () => {
  console.log('form', form)
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    let itemNames: string = form.itemNames
      .map((i) => itemNamesOptions.value.find((j) => j.value === i)?.label)
      .join(',')
    let orgFrom = form.orgFrom
      .map((i) => orgFromOptions.value.find((j) => j.value === i)?.label)
      .join(',')
    let orgFromIds = form.orgFrom
      .map((i) => orgFromOptions.value.find((j) => j.value === i)?.value)
      .join(',')
    let spotCheckTime = form.spotCheckTime?.length
      ? form.spotCheckTime[0]
      : undefined
    let spotCheckEndTime = form.spotCheckTime?.length
      ? form.spotCheckTime[1]
      : undefined
    let data = {
      ...otherData.value,
      operPersonIds: form.operPersonIds.map((i) => i.value).join(','),
      operPersonNames: form.operPersonIds.map((i) => i.name).join(','),
      itemIds: form.itemNames.join(','),
      itemNames,
      orgFromIds,
      orgFrom,
      spotCheckTime,
      spotCheckEndTime
    }
    console.log('data', data)
    loading.value = true
    intelligentSave(data)
      .then((res) => {
        emit('reload')
        formCancel()
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const clearForm = () => {
  form.spotCheckTime = undefined
  form.orgFrom = []
  form.orgFromIds = ''
  form.itemNames = []
  form.operPersonIds = []
  form.types = 0
  nextTick(() => {
    ruleFormRef.value.resetFields()
  })
}

// 取消
function cancel() {
  formCancel()
}

const back = () => {
  clearForm()
  formVisible.value = false
}
defineExpose({ show })
</script>

<style scoped lang="scss">
.search {
  display: flex;
  justify-content: space-between;
}
.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}
.select {
  width: 100% !important;
}
.box-item {
  margin-left: 20px;
  cursor: pointer;
}
</style>
